package cn.wmx.boot;

import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

// 不敢吭声
public class MySpringServletContainerInitializer implements ServletContainerInitializer {
    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
        List<WebApplicationInitializer> list = new LinkedList<>();
        if (set != null) {
            for (Class<?> aClass : set) {
                if (!aClass.isInterface()
                        && !Modifier.isAbstract(aClass.getModifiers())
                        && WebApplicationInitializer.class.isAssignableFrom(aClass)) {
                    try {
                        list.add((WebApplicationInitializer) ReflectionUtils.accessibleConstructor(aClass).newInstance());
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        if (list.isEmpty()) return;

        AnnotationAwareOrderComparator.sort(list);
        for (WebApplicationInitializer initializer : list) {
            initializer.onStartup(servletContext);
        }

    }
}
